package com.example.gate.websocket;

import com.example.game.CReq;
import com.example.game.CResp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: Allen
 * @create: 2025/7/14 16:30
 * @description:
 **/
@Slf4j
public class WSClientProtobufDecoder  extends MessageToMessageDecoder<WebSocketFrame> {


    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
        if (frame instanceof BinaryWebSocketFrame) {
            BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
            ByteBuf content = binaryFrame.content();

            if (content.readableBytes() < 4) {
                return;
            }
            content.markReaderIndex();
            int secret = content.readInt();//加密类型
            int length = content.readInt();//包体长度
            if (content.readableBytes() < length) {
                content.resetReaderIndex();
                return;
            }

            byte[] data = new byte[length];
            content.readBytes(data);
            try {
                CReq request = CReq.parseFrom(data);
                out.add(request);
            } catch (Exception e) {
                log.error("Protobuf解码失败", e);
            }
        } else {
            log.warn("收到非二进制WebSocket帧: {}", frame.getClass().getSimpleName());
        }
    }
}
